package cn.aihongbo.kmp.data.vm

import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import cn.aihongbo.kmp.base.vm.HViewModel
import cn.aihongbo.kmp.data.bean.CityBean
import cn.aihongbo.kmp.data.bean.ClassicTravelBean
import cn.aihongbo.kmp.data.bean.HbcConfigBannerItemBean
import cn.aihongbo.kmp.data.bean.HbcConfigOperationGiftBean
import cn.aihongbo.kmp.data.bean.TravelDictBean
import cn.aihongbo.kmp.data.repository.BicsRepository
import kotlinx.coroutines.flow.catch

class HomeViewModel(private val repository: BicsRepository) : HViewModel() {
    private val _banners = mutableStateListOf<HbcConfigBannerItemBean>()
    val banners: List<HbcConfigBannerItemBean> = _banners

    //当季热门
    private val _redHotBanners = mutableStateListOf<HbcConfigBannerItemBean>()
    val redHotBanners: List<HbcConfigBannerItemBean> = _redHotBanners

    //新客户优惠券
    val operationGift = mutableStateOf<HbcConfigOperationGiftBean?>(null)

    //经典玩法分组
    val travelDict = mutableStateListOf<TravelDictBean?>()

    //展示的经典行程
    val classicTravel = mutableStateListOf<ClassicTravelBean?>()

    //    =============选中数据=====================
    var selectedCity = mutableStateOf<CityBean?>(CityBean(217, "东京"))

    fun loadBanners() {
        net {
            repository.getHomeTopImageBanner().collect { response ->
                response.list?.let { _banners.addAll(it) }
            }
        }
    }

    /**
     * 当季热门
     */
    fun loadRedHotBanner() {
        net {
            repository.getHomeRedHotBanner().collect { it ->
                it.list?.let { _redHotBanners.addAll(it) }
            }
        }
    }

    fun loadOperationGift() {
        net {
            repository.getHomeConfigOperationGift().collect { it ->
                operationGift.value = it
            }
        }
    }

    /**
     * 经典玩法分组
     */
    fun loadQueryTravelDict() {
        net {
            repository.getHomeQueryTravelDict().collect {
                travelDict.addAll(it)
                if (classicTravel.isEmpty()) {
                    loadQueryClassicTravel(it[0])
                }
            }
        }
    }

    /**
     * 查询经典行程
     */
    fun loadQueryClassicTravel(group: TravelDictBean?) {
        net {
            repository.getClassicTravel(group).catch {
                println(it.message)
            }.collect {
                classicTravel.clear()
                it.list?.let { elements -> classicTravel.addAll(elements) }
            }
        }
    }
}